package cn.hdu.liang.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

class Server implements Runnable {
    @Override
    public void run() {
        try(DatagramChannel channel = DatagramChannel.open()) {
            channel.socket().bind(new InetSocketAddress(8888));
            ByteBuffer buffer = ByteBuffer.allocate(48);
            buffer.clear();
            channel.receive(buffer);
            buffer.flip();
            while(buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
            System.out.println();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

class Client implements Runnable {
    @Override
    public void run() {

        try(DatagramChannel channel = DatagramChannel.open()) {
            ByteBuffer buffer = ByteBuffer.allocate(48);
            buffer.clear();
            buffer.put("hehe101x".getBytes());
            buffer.flip();
            channel.send(buffer, new InetSocketAddress("localhost", 8888));
        } catch(IOException e) {
            e.printStackTrace();
        }

    }
}


public class DatagramChannelTest {
    public static void main(String[] args) throws InterruptedException {
        new Thread(new Server()).start();
        Thread.sleep(1000);
        new Thread(new Client()).start();
        Thread.sleep(1000);
    }
}
